package com.pureut.storage.service.impl;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.storage.domain.*;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.PickingOutsourceExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.UpdateDocVo;
import com.pureut.storage.vo.*;
import com.pureut.system.api.*;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysUser;
import com.pureut.system.api.vo.SubcontractReceiptOtherVo;
import com.pureut.system.api.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2022/12/28  11:01
 */
@Service
public class PickingOutsourceServiceImpl extends ServiceImpl<PickingOutsourceMapper, PickingOutsource> implements PickingOutsourceService {


    //委外发货
    @Resource
    PickingOutsourceMapper pickingOutsourceMapper;

    @Resource
    ProductionPickingService productionPickingService;

    //基础模块
    @Resource
    FeignService feignService;

    //仓库建模
    @Resource
    WarehouseMapper warehouseMapper;

    @Resource
    OrderFeignService orderFeignService;

    //单据配置
    @Resource
    private SystemDocumentFeignService systemDocumentFeignService;

    //库存
    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;

    //出库service
    @Resource
    WmsStockInfoService wmsStockInfoService;

    //委外发货明细
    @Resource
    PickingOutsourceDetailMapper pickingOutsourceDetailMapper;

    //委外发货明细
    @Resource
    PickingOutsourceDetailService pickingOutsourceDetailService;

    //公共物料
    @Resource
    PublicGoodsMapper publicGoodsMapper;

    //用户信息
    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private QualityFeginService qualityFeginService;

    @Resource
    private PickingSchemeService pickingSchemeService;

    @Resource
    private OutboundLogService outboundLogService;

    @Resource
    private OutboundLogMapper outboundLogMapper;


    /**
     * 委外发货新增
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOutsource(PickingOutsourceVo pickingOutsourceVo) throws Exception {
        List<PickingOutsourceRelationVo> list = pickingOutsourceVo.getList();


        List pickingOutsourcelist = new ArrayList<PickingOutsource>();
        if (list.size() > 0) {

            for (PickingOutsourceRelationVo pickingOutsourceRelationVo : list) {

                String sn = feignService.getAuthorityCoding("warehouse:outbound:subcontract:list");
                if (sn == null) {
                    throw new GlobalException("该单据未进行配置,无法生成单据编码");
                }

                PickingOutsource pickingOutsource = new PickingOutsource();
                BeanUtils.copyProperties(pickingOutsourceVo, pickingOutsource);
                BeanUtils.copyProperties(pickingOutsourceRelationVo, pickingOutsource);
                pickingOutsource.setCreateUser(SecurityUtils.getUsername())
                        .setCreateTime(new Date())
                        .setDocumentType(DocumentTypeEnum.PICKING_OUTSOURCE.getCode())
                        .setWodDocNum(sn)
                        .setDeptId(SecurityUtils.getDeptId())
                        .setWodStatus(1)
                        .setConnectionId(pickingOutsourceRelationVo.getConnectionId())
                        .setGenerationMode(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                pickingOutsourcelist.add(pickingOutsource);
            }
            return saveBatch(pickingOutsourcelist);
        } else {
            throw new GlobalException("请至少添加一条物料明细");
        }
    }

    /**
     * 修改委外发货
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOutsource(PickingOutsourceVo pickingOutsourceVo) {

        //查询当前id对应的单据
        PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingOutsourceVo.getId());

        int wodStatus = pickingOutsource.getWodStatus();
        if (wodStatus != 1 && wodStatus != 4) {
            throw new GlobalException("只能对状态为“待提交”和“待审核”的单据进行修改");
        }

        if (wodStatus == 4) {

            //调用审核
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            String perms = "warehouse:outbound:subcontract:examine";
            String auditDoc = pickingOutsource.getWodDocNum();
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setPerms(perms);
            AjaxResult history = feignService.editHistory(sysAuditHistoryVo);
            String data = JSON.parseObject(JSON.toJSONString(history.get("msg")), String.class);
            if ("操作成功".equals(data)) {

                //修改审核代办状态为已处理
                feignService.updateStatus(3, pickingOutsource.getWodDocNum(), "委外发货");//

                pickingOutsource.setWodStatus(1);
            }
        }
        //设置修改的值
        pickingOutsource.setTransceiverType(pickingOutsourceVo.getTransceiverType());
        //设置加工商
        pickingOutsource.setFabricatorsId(pickingOutsourceVo.getFabricatorsId());
        //设置备注
        pickingOutsource.setRemark(pickingOutsourceVo.getRemark());

        List<PickingOutsourceRelationVo> list = pickingOutsourceVo.getList();
        PickingOutsourceRelationVo pickingOutsourceRelationVo = list.get(0);

        //设置委外订单号
        pickingOutsource.setConnectionId(pickingOutsourceRelationVo.getConnectionId());
        //设置计划量
        pickingOutsource.setPlannedWeight(pickingOutsourceRelationVo.getPlannedWeight());
        //设置出库仓
        pickingOutsource.setOutOfStock(pickingOutsourceRelationVo.getOutOfStock());
        return updateById(pickingOutsource);

    }

    /**
     * 关结委外发货
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean closeOutsource(PickingOutsourceVo pickingOutsourceVo) {


        //已完成已关结单据不可重复关结
        PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingOutsourceVo.getId());

        Integer wodStatus = pickingOutsource.getWodStatus();

        if (wodStatus == 8 || wodStatus == 7) {
            throw new GlobalException("不可对已关结和已完成状态的单据进行重复关结");
        }


        try {
            //如果单据状态是待检验，入库的物料显示在库，关联品质检验单状态更新为撤销
            if (wodStatus == 9 || wodStatus == 10 || wodStatus == 6) {
                //根据单号获取生产领料单明细
                List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                ArrayList<WmsStockInfo> wmsStockInfos = new ArrayList<>();

                for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
                    wmsStockInfos.add(wmsStockInfo);
                }

                if (wmsStockInfos.size() != 0) {
                    boolean b = wmsStockInfoService.removeBatchByIds(wmsStockInfos);
                }


                if (wodStatus == 9) {
                    //如果是待检验删除品质检验单
                    UpdateQualityStatusVo updateQualityStatusVo = new UpdateQualityStatusVo();
                    updateQualityStatusVo.setStatus(8);
                    updateQualityStatusVo.setAssociatedNo(pickingOutsource.getWodDocNum());
                    AjaxResult ajaxResult = qualityFeginService.updateQualityInspectionDocument(updateQualityStatusVo);


                    if (!"200".equals(ajaxResult.get("code").toString())) {
                        throw new GlobalException("服务调用失败");
                    }

                }
            }
        } catch (Exception e) {
            throw new GlobalException("关结失败");
        }


        //取出关结人
        String closeMan = pickingOutsource.getCloseMan();
        if (closeMan != null) {
            closeMan = closeMan + "," + SecurityUtils.getUsername();
        } else {
            closeMan = SecurityUtils.getUsername();
        }

        //修改单据状态未关结，修改关结原因，修改关结人，修改关结时间
        PickingOutsource pickingOutsource1 = new PickingOutsource();
        pickingOutsource1.setId(pickingOutsourceVo.getId())
                .setWodStatus(8).setCloseTime(new Date())
                .setCloseMan(closeMan)
                .setCloseCause(pickingOutsourceVo.getCloseCause());
        return updateById(pickingOutsource1);
    }

    /**
     * 委外发货删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOutsource(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        //根据ids批量查询出list列表
        List<PickingOutsource> pickingOutsources = pickingOutsourceMapper.selectBatchIds(idStr);

        //遍历
        for (PickingOutsource pickingOutsource : pickingOutsources) {
            if (pickingOutsource.getWodStatus() != 1 && pickingOutsource.getWodStatus() != 4) {
                throw new GlobalException("只能删除“待提交”或“未通过”状态的单据");
            } else if (pickingOutsource.getGenerationMode() != 2) {
                throw new GlobalException("系统自动生成的单据不可删除");
            }
        }

        for (PickingOutsource pickingOutsource : pickingOutsources) {
            feignService.deleteDoc(pickingOutsource.getWodDocNum(), "委外出库");
        }
        return removeBatchByIds(idStr);
    }

    /**
     * 提交审核
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitOutsource(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        //根据ids批量查询出list列表
        List<PickingOutsource> pickingOutsources = pickingOutsourceMapper.selectBatchIds(idStr);

        //遍历
        for (PickingOutsource pickingOutsource : pickingOutsources) {
            if (pickingOutsource.getWodStatus() != 1) {
                throw new GlobalException("只能对状态为“待提交”的单据进行提交操作");
            }
            pickingOutsource.setWodStatus(2);

            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
            sysWorkbenchAuditAgentVo.setDocConfig("warehouse:outbound:subcontract:examine");
            sysWorkbenchAuditAgentVo.setReceiptName("委外发货");
            sysWorkbenchAuditAgentVo.setReceiptNumber(pickingOutsource.getWodDocNum());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);
        }


        return updateBatchById(pickingOutsources);
    }

    /**
     * 查看单据
     *
     * @param id
     * @return
     */
    @Override
    public PickingOutsourceDto view(Long id) {
        //查询单条对象
        PickingOutsourceDto pickingOutsourceDto = pickingOutsourceMapper.getPickingOutsourceById(id);
        //根据字典查询收发类型
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_outsource_type");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        //添加单据类型
        pickingOutsourceDto.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(pickingOutsourceDto.getDocumentType())));
        pickingOutsourceDto.setDocumentType(pickingOutsourceDto.getDocumentType());

        //添加收发类型
        pickingOutsourceDto.setTransceiverType(pickingOutsourceDto.getTransceiverType() + "");
        pickingOutsourceDto.setTransceiverTypeDict(statusMap.get(pickingOutsourceDto.getTransceiverType() + ""));

        //获取明细列表
        List<PickingOutsourceViewDto> list = new ArrayList<>();

        PickingOutsourceViewDto pickingOutsourceViewDto = new PickingOutsourceViewDto();


        //查看仓库名称
        Warehouse warehouse = warehouseMapper.selectById(pickingOutsourceDto.getOutOfStock());
        if (warehouse != null) {
            //添加仓库名称
            pickingOutsourceViewDto.setOutOfStockDict(warehouse.getWarehouseName());
            pickingOutsourceViewDto.setOutOfStock(pickingOutsourceDto.getOutOfStock());
        }

        //添加单位key
        pickingOutsourceViewDto.setMaterialUnit(pickingOutsourceDto.getMaterialUnit() + "");
        //添加单位值
        pickingOutsourceViewDto.setMaterialUnitDict(unitMap.get(pickingOutsourceDto.getMaterialUnit() + ""));

        //添加物料名称,物料规格,物料编码
        pickingOutsourceViewDto.setMaterialCode(pickingOutsourceDto.getMaterialCode());
        pickingOutsourceViewDto.setMaterialName(pickingOutsourceDto.getItemName());
        pickingOutsourceViewDto.setMaterialSpec(pickingOutsourceDto.getItemSpec());

        //添加计划量
        pickingOutsourceViewDto.setPlannedWeight(pickingOutsourceDto.getPlannedWeight());
        //添加委外订单号
        pickingOutsourceViewDto.setConnectionId(pickingOutsourceDto.getConnectionId());

        list.add(pickingOutsourceViewDto);
        pickingOutsourceDto.setList(list);
        return pickingOutsourceDto;
    }

    /**
     * 查询委外出库列表
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<PickingOutsourceDto> getList(PickingOutsourceVo pickingOutsourceVo) {
        //查询委外出库列表
        List<PickingOutsourceDto> pickingOutsourceList = pickingOutsourceMapper.getPickingOutsourceList(pickingOutsourceVo);

        //获取单据状态字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_outsource_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出收发类型
        List<SysDictData> receivType = DictUtils.getDictCache("picking_outsource_type");
        Map<String, String> typeMap = receivType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (PickingOutsourceDto pickingOutsourceDto : pickingOutsourceList) {

            //查看仓库名称
            Warehouse warehouse = warehouseMapper.selectById(pickingOutsourceDto.getOutOfStock());
            if (warehouse != null && warehouse.getWarehouseName() != null) {
                //添加仓库名称
                pickingOutsourceDto.setOutOfStockDict(warehouse.getWarehouseName());
            }
            pickingOutsourceDto.setOutOfStock(pickingOutsourceDto.getOutOfStock());
            //添加单据类型
            pickingOutsourceDto.setDocumentType(DocumentTypeEnum.getValue(Integer.parseInt(pickingOutsourceDto.getDocumentType())));

            //添加单位key
            pickingOutsourceDto.setMaterialUnitDict(pickingOutsourceDto.getMaterialUnit() + "");
            //添加单位值
            pickingOutsourceDto.setMaterialUnit(unitMap.get(pickingOutsourceDto.getMaterialUnit() + ""));


            //添加收发类型
            pickingOutsourceDto.setTransceiverTypeDict(pickingOutsourceDto.getTransceiverType() + "");
            pickingOutsourceDto.setTransceiverType(typeMap.get(pickingOutsourceDto.getTransceiverType() + ""));


            //添加生产方式
            pickingOutsourceDto.setGenerationMode(GenerationMethodEnum.getValue(Integer.parseInt(pickingOutsourceDto.getGenerationMode())));

            //添加单据状态
            pickingOutsourceDto.setWodStatusDict(pickingOutsourceDto.getWodStatus() + "");
            pickingOutsourceDto.setWodStatus(statusMap.get(pickingOutsourceDto.getWodStatus() + ""));

        }
        return pickingOutsourceList;
    }

    /**
     * 查询委外出库列表
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<GetPdaDto> getListPda(PickingOutsourceVo pickingOutsourceVo) {
        //查询委外出库列表
        List<GetPdaDto> list = pickingOutsourceMapper.getPickingOutsourceListPda(pickingOutsourceVo);

        //获取单据状态字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_outsource_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (GetPdaDto getPdaDto : list) {
            getPdaDto.setWodStatusDict(statusMap.get(getPdaDto.getWodStatus()));
        }

        return list;
    }


    /**
     * 导出
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Override
    public List<PickingOutsourceExport> getInfoExport(PickingOutsourceVo pickingOutsourceVo) {

        if (pickingOutsourceVo.getIdStr() != null) {
            List<String> idList = Arrays.asList(pickingOutsourceVo.getIdStr().split(","));

            pickingOutsourceVo.setIds(idList);
        }

        List<PickingOutsourceExport> list = pickingOutsourceMapper.getInfoExport(pickingOutsourceVo);

        //根据字典查出收发类型
        List<SysDictData> receivType = DictUtils.getDictCache("picking_outsource_type");
        Map<String, String> typeMap = receivType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (PickingOutsourceExport pickingOutsourceExport : list) {
            pickingOutsourceExport.setTransceiverTypeDict(typeMap.get(pickingOutsourceExport.getTransceiverTypeDict()));
        }

        return list;
    }

    /**
     * 委外发货出库Pda
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto out(PickingRestDbVo pickingRestDbVo) throws Exception {
        //出库类型
        String type = pickingRestDbVo.getType();
        //输入值
        String inputValue = pickingRestDbVo.getInputValue();

        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();

        //判断是否超收或者超发
        //获取菜单id
        Long menuId = feignService.getIdByMenuName("委外发货");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //如果配置了送检,则校验是否配了检验方案
        if (sysDocument.getDocInspectionMark() == 1) {

            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
            if (documentCheckDtoList == null) {
                throw new GlobalException("请先在单据配置中配置送检方案");
            }


            PickingOutsource byId = getById(pickingRestDbVo.getId());

            //查询单位
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, byId.getMaterialCode()));


            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
            qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
            qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
            qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
            qualitySchemeConfigurationVo.setMaterialCode(byId.getMaterialCode());
            boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

            if (!check) {
                throw new GlobalException("该物料不存在对应的检验方案");

            }
        }


        //如果是扫码出库
        if ("1".equals(type)) {
            //判断扫描的物料条码是否一致
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2));
            if (wmsStockInfo == null) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                return pickingRestDbDto;
            }

            if ("1".equals(wmsStockInfo.getWsiFreezeInfo())) {
                throw new GlobalException("此物料已冻结请重新输入");
            }

            //扫描的物料编码
            String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();
            //查询委外发货单中的物料编码、
            PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());

            if (!pickingOutsource.getMaterialCode().equals(wsiMaterialCode)) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                return pickingRestDbDto;
            }

            //判断是否重复扫描(在明细表中查询是否有该条码)
            PickingOutsourceDetail pickingOutsourceDetail1 = pickingOutsourceDetailMapper.selectOne(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getMaterialNumber, inputValue).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
            if (pickingOutsourceDetail1 != null) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("请勿重复扫描");
                return pickingRestDbDto;
            }

            PickingOutsourceDetail pickingOutsourceDetail = new PickingOutsourceDetail();

            //物料号码
            pickingOutsourceDetail.setMaterialNumber(inputValue);

            //物料编码
            pickingOutsourceDetail.setMaterialCode(wmsStockInfo.getWsiMaterialCode());

            //物料状态
            pickingOutsourceDetail.setStatus("3");

            //关联单号
            pickingOutsourceDetail.setWodDocNum(pickingOutsource.getWodDocNum());

            //毛重
            pickingOutsourceDetail.setGrossWeight(wmsStockInfo.getWsiGorssWeight());

            //净重
            pickingOutsourceDetail.setTheWeight(wmsStockInfo.getWsiNetWeight());

            //出库数量
            pickingOutsourceDetail.setOutgoingNumber(wmsStockInfo.getWsiMaterialNum());

            //批次号
            pickingOutsourceDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());

            //供应商编码
            pickingOutsourceDetail.setSupplierCode(wmsStockInfo.getWsiSupplierCode());

            //仓储信息
            pickingOutsourceDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());

            //出库人
            pickingOutsourceDetail.setDepositor(SecurityUtils.getUsername());

            //出库时间
            pickingOutsourceDetail.setDeliveryTime(new Date());


            //判断是否有检验
            int docInspectionMark = sysDocument.getDocInspectionMark();
            //如果有检验
            if (docInspectionMark == 1) {
                //修改单据明细为待检验
                pickingOutsourceDetail.setStatus("1");
            } else {
                //判断是否有交接
                int docHandoverMark = sysDocument.getDocHandoverMark();
                //有交接
                if (docHandoverMark == 1) {
                    //修改单据明细为待交接
                    pickingOutsourceDetail.setStatus("2");

                }
            }
            //添加明细
            pickingOutsourceDetailMapper.insert(pickingOutsourceDetail);

            //查询单位
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource.getMaterialCode()));


            //修改委外发货单的单据状态为出库中
            pickingOutsource.setWodStatus(6);
            //修改出库重量和出库数量
            Double outgoingWeight = pickingOutsource.getOutgoingWeight();
            if (outgoingWeight == null) {
                outgoingWeight = 0.0;
            }
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(outgoingWeight));

            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));

            BigDecimal add = bigDecimal.add(bigDecimal1);
            pickingOutsource.setOutgoingWeight(add.doubleValue());

            Integer num = pickingOutsource.getOutgoingNumber();
            if (num == null) {
                num = 0;
            }
            pickingOutsource.setOutgoingNumber(num + 1);
            //判断单位是否是kg
            if ("2".equals(publicGoods.getMaterialUnit())) {
                //实际量
                pickingOutsource.setActualNumber(pickingOutsource.getOutgoingWeight());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                //实际量
                BigDecimal dun = new BigDecimal("1000");
                BigDecimal outNum = new BigDecimal(String.valueOf(pickingOutsource.getOutgoingWeight()));
                BigDecimal divide = outNum.divide(dun);
                pickingOutsource.setActualNumber(divide.doubleValue());
            } else {
                //实际量
                pickingOutsource.setActualNumber(Double.parseDouble(pickingOutsource.getOutgoingNumber() + ""));
            }
            updateById(pickingOutsource);

            //修改仓库物料的状态为备料
            wmsStockInfo.setWsiMaterialStatus(5);
            int i = wmsStockInfoMapper.updateById(wmsStockInfo);


            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(pickingOutsource.getPlannedWeight() + "/" + pickingOutsource.getActualNumber() + unitMap.get(publicGoods.getMaterialUnit()));
            //出库数量
            pickingRestDbDto.setAllotNumOut(pickingOutsource.getOutgoingNumber() + "");

            pickingRestDbDto.setMessage("物料号码:" + inputValue + ",净重:" + wmsStockInfo.getWsiNetWeight() + ",数量:1" + "录入成功");

            pickingRestDbDto.setCode("200");
            pickingRestDbDto.setPickingPrompt(point(pickingOutsource.getId()).getCombinationName());
            OutboundLog outboundLog = new OutboundLog();
            BeanUtils.copyProperties(wmsStockInfo, outboundLog, new String[]{"id"});
            outboundLogService.save(outboundLog);

            UpdateSubcontractingOrderDataVo updateSubcontractingOrderDataVo = new UpdateSubcontractingOrderDataVo();
            updateSubcontractingOrderDataVo.setOutWeight(wmsStockInfo.getWsiNetWeight());
            updateSubcontractingOrderDataVo.setMaterialCode(pickingOutsource.getMaterialCode());
            updateSubcontractingOrderDataVo.setSubcontractingOrderNumber(pickingOutsource.getConnectionId());
            boolean b = orderFeignService.updateSubcontractingOrderData(updateSubcontractingOrderDataVo);
            if (!b) {
                throw new GlobalException("委外订单服务调用失败");
            }

            //查询当前生产领料单
            PickingOutsource pickingOutsource1 = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());
            //判断是否有超收
            int docHairMark = sysDocument.getDocHairMark();
            //没有超收
            if (docHairMark != 1) {

                //如果是kg
                if ("2".equals(publicGoods.getMaterialUnit()) || "3".equals(publicGoods.getMaterialUnit())) {
                    //计划出库重量
                    Double allotAmount = pickingOutsource1.getPlannedWeight();
                    //实际出库重量
                    Double allotWeightOut = pickingOutsource1.getActualNumber();
                    if (allotWeightOut >= allotAmount) {
                        //判断是否有检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingOutsource1.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingOutsource1.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(2);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingOutsourceDetail> stockOutInfoDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getMaterialNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingOutsource1.setWodStatus(9);
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据为待交接
                            pickingOutsource1.setWodStatus(10);
                            pickingOutsourceMapper.updateById(pickingOutsource1);

                        } else {
                            //修改单据为已完成
                            pickingOutsource1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                        }
                    }
                } else {
                    //计划出库重量
                    Double allotAmount = pickingOutsource1.getPlannedWeight();

                    //实际出库数量
                    int allotNumOut = pickingOutsource1.getOutgoingNumber();
                    if (allotNumOut >= allotAmount) {
                        //判断是否检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingOutsource1.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingOutsource1.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(2);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingOutsourceDetail> stockOutInfoDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getMaterialNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingOutsource1.setWodStatus(9);
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据明细为待交接
                            pickingOutsource1.setWodStatus(10);
                            pickingOutsourceMapper.updateById(pickingOutsource1);

                        } else {
                            //修改单据状态为已完成
                            pickingOutsource1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                        }
                    }
                }
            }


        } else if ("2".equals(type)) {
            //批次出库
            //查询当前批次对应单条码信息
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2).notIn(WmsStockInfo::getWsiFreezeInfo, 1));

            if (wmsStockInfoList.size() == 0) {
                pickingRestDbDto.setMessage("扫描失败，当前批次在库存中为0");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            //查询当前批次(在库的重量之和)
            Double netWeight = wmsStockInfoMapper.getNetWeight(inputValue);

            //查询委外出库单中的物料编码
            PickingOutsource pickingOutsource11 = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());

            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource11.getMaterialCode()));

            List<PickingOutsourceDetail> list = new ArrayList<PickingOutsourceDetail>();

            List<OutboundLog> outboundLogList = new ArrayList<>();


            for (WmsStockInfo wmsStockInfo : wmsStockInfoList) {


                //扫描的物料编码
                String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();

                if (!pickingOutsource11.getMaterialCode().equals(wsiMaterialCode)) {
                    pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                    pickingRestDbDto.setCode("500");
                    return pickingRestDbDto;
                }


                //新增生产领料明细
                PickingOutsourceDetail pickingOutsourceDetail = new PickingOutsourceDetail();

                //物料号码
                pickingOutsourceDetail.setMaterialNumber(wmsStockInfo.getWsiMaterialNumber());

                //物料状态
                pickingOutsourceDetail.setStatus("3");

                //关联单号
                pickingOutsourceDetail.setWodDocNum(pickingOutsource11.getWodDocNum());

                //物料编码
                pickingOutsourceDetail.setMaterialCode(wmsStockInfo.getWsiMaterialCode());

                //毛重
                pickingOutsourceDetail.setGrossWeight(wmsStockInfo.getWsiGorssWeight());

                //净重
                pickingOutsourceDetail.setTheWeight(wmsStockInfo.getWsiNetWeight());

                //出库数量
                pickingOutsourceDetail.setOutgoingNumber(wmsStockInfo.getWsiMaterialNum());

                //批次号
                pickingOutsourceDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());

                //供应商编码
                pickingOutsourceDetail.setSupplierCode(wmsStockInfo.getWsiSupplierCode());

                //仓储信息
                pickingOutsourceDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());

                //出库人
                pickingOutsourceDetail.setDepositor(SecurityUtils.getUsername());

                //出库时间
                pickingOutsourceDetail.setDeliveryTime(new Date());


                //判断是否有检验
                int docInspectionMark = sysDocument.getDocInspectionMark();
                //如果有检验
                if (docInspectionMark == 1) {
                    //修改单据明细为待检验
                    pickingOutsourceDetail.setStatus("1");
                } else {
                    //判断是否有交接
                    int docHandoverMark = sysDocument.getDocHandoverMark();
                    //有交接
                    if (docHandoverMark == 1) {
                        //修改单据明细为待交接
                        pickingOutsourceDetail.setStatus("2");
                    }
                }
                list.add(pickingOutsourceDetail);

                //修改生产领料单的单据状态为出库中
                pickingOutsource11.setWodStatus(6);
                //修改出库重量和出库数量
                Double outgoingWeight = pickingOutsource11.getOutgoingWeight();
                if (outgoingWeight == null) {
                    outgoingWeight = 0.0;
                }
                BigDecimal bigDecimal = new BigDecimal(String.valueOf(outgoingWeight));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));

                BigDecimal add = bigDecimal.add(bigDecimal1);
                pickingOutsource11.setOutgoingWeight(add.doubleValue());

                Integer outgoingNumber = pickingOutsource11.getOutgoingNumber();
                if (outgoingNumber == null) {
                    outgoingNumber = 0;
                }
                pickingOutsource11.setOutgoingNumber(outgoingNumber + 1);


                //修改仓库物料的状态为备料
                wmsStockInfo.setWsiMaterialStatus(5);

                OutboundLog outboundLog = new OutboundLog();
                BeanUtils.copyProperties(wmsStockInfo, outboundLog, new String[]{"id"});
                outboundLogList.add(outboundLog);

            }

            //添加明细
            pickingOutsourceDetailService.saveBatch(list);
            //修改仓库物料状态
            wmsStockInfoService.updateBatchById(wmsStockInfoList);

            //判断单位是否是kg
            if ("2".equals(publicGoods.getMaterialUnit())) {
                //实际量
                pickingOutsource11.setActualNumber(pickingOutsource11.getOutgoingWeight());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                //实际量
                BigDecimal dun = new BigDecimal("1000");
                BigDecimal outNum = new BigDecimal(String.valueOf(pickingOutsource11.getOutgoingWeight()));
                BigDecimal divide = outNum.divide(dun);
                pickingOutsource11.setActualNumber(divide.doubleValue());
            } else {
                //实际量
                pickingOutsource11.setActualNumber(Double.parseDouble(pickingOutsource11.getOutgoingNumber() + ""));
            }

            updateById(pickingOutsource11);


            PickingOutsource pickingOutsource1 = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());
            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(pickingOutsource1.getPlannedWeight() + "/" + pickingOutsource1.getActualNumber() + unitMap.get(publicGoods.getMaterialUnit()));
            //出库数量
            pickingRestDbDto.setAllotNumOut(pickingOutsource1.getOutgoingNumber() + "");


            pickingRestDbDto.setMessage("批次号:" + inputValue + ",总净重:" + netWeight + ",数量:" + wmsStockInfoList.size() + "录入成功");

            UpdateSubcontractingOrderDataVo updateSubcontractingOrderDataVo = new UpdateSubcontractingOrderDataVo();
            updateSubcontractingOrderDataVo.setOutWeight(netWeight);
            updateSubcontractingOrderDataVo.setMaterialCode(pickingOutsource1.getMaterialCode());
            updateSubcontractingOrderDataVo.setSubcontractingOrderNumber(pickingOutsource1.getConnectionId());
            boolean b = orderFeignService.updateSubcontractingOrderData(updateSubcontractingOrderDataVo);
            if (!b) {
                throw new GlobalException("委外订单服务调用失败");
            }

            pickingRestDbDto.setCode("200");
            pickingRestDbDto.setPickingPrompt(point(pickingOutsource1.getId()).getCombinationName());
            outboundLogService.saveBatch(outboundLogList);


            //判断是否有超收
            int docHairMark = sysDocument.getDocHairMark();
            //没有超发
            if (docHairMark != 1) {

                //如果是kg
                if ("2".equals(publicGoods.getMaterialUnit()) || "3".equals(publicGoods.getMaterialUnit())) {
                    //计划出库重量
                    Double allotAmount = pickingOutsource1.getPlannedWeight();
                    //实际出库重量
                    Double allotWeightOut = pickingOutsource1.getActualNumber();
                    if (allotWeightOut >= allotAmount) {
                        //判断是否有检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingOutsource1.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingOutsource1.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(2);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingOutsourceDetail> stockOutInfoDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource1.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getMaterialNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingOutsource1.setWodStatus(9);
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据为待交接
                            pickingOutsource1.setWodStatus(10);
                            pickingOutsourceMapper.updateById(pickingOutsource1);

                        } else {
                            //修改单据为已完成
                            pickingOutsource1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 5));
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                        }
                    }
                } else {
                    //计划出库重量
                    double allotAmount = pickingOutsource1.getPlannedWeight();
                    //实际出库数量
                    int allotNumOut = pickingOutsource1.getOutgoingNumber();
                    if (allotNumOut >= allotAmount) {
                        //判断是否检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingOutsource1.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingOutsource1.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(2);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingOutsourceDetail> stockOutInfoDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource1.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getMaterialNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingOutsource1.setWodStatus(9);
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据明细为待交接
                            pickingOutsource1.setWodStatus(10);
                            pickingOutsourceMapper.updateById(pickingOutsource1);

                        } else {
                            //修改单据状态为已完成
                            pickingOutsource1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 5));
                            pickingOutsourceMapper.updateById(pickingOutsource1);
                        }
                    }
                }
            }

        } else if ("3".equals(type)) {
            //条码撤销
            PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());

            if (pickingOutsource.getWodStatus() != 5 && pickingOutsource.getWodStatus() != 6) {
                throw new GlobalException("只能对待出库和出库中的单据进行条码撤销");
            }

            //在明细表中查询是否有此条码
            PickingOutsourceDetail pickingOutsourceDetail = pickingOutsourceDetailMapper.selectOne(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getMaterialNumber, inputValue).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
            if (pickingOutsourceDetail == null) {
                pickingRestDbDto.setMessage("撤销失败");
                return pickingRestDbDto;
            }
            //修改库存状态为在库
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
            wmsStockInfo.setWsiMaterialStatus(2);
            wmsStockInfoMapper.updateById(wmsStockInfo);

            OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, inputValue));
            //删除日志
            outboundLogService.removeById(outboundLog);

            //删除出库明细
            int delete = pickingOutsourceDetailMapper.delete(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getMaterialNumber, inputValue).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));


            BigDecimal out = new BigDecimal(String.valueOf(pickingOutsource.getOutgoingWeight()));
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));
            BigDecimal outWeight = out.subtract(bigDecimal);
            //修改出库重量
            pickingOutsource.setOutgoingWeight(outWeight.doubleValue());

            //扣除数量
            int num = pickingOutsource.getOutgoingNumber();
            pickingOutsource.setOutgoingNumber(num - 1);

            //查询单位
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource.getMaterialCode()));

            //实际出库重量
            if ("2".equals(publicGoods.getMaterialUnit())) {

                BigDecimal sj = new BigDecimal(String.valueOf(pickingOutsource.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                pickingOutsource.setActualNumber(sjWeight.doubleValue());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                BigDecimal sj = new BigDecimal(String.valueOf(pickingOutsource.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight())).divide(new BigDecimal("1000"));
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                pickingOutsource.setActualNumber(sjWeight.doubleValue());
            } else {
                BigDecimal sj = new BigDecimal(String.valueOf(pickingOutsource.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal("1");
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                pickingOutsource.setActualNumber(sjWeight.doubleValue());

            }

            int i = pickingOutsourceMapper.updateById(pickingOutsource);
            if (i <= 0) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("撤销失败");
                return pickingRestDbDto;
            }

            UpdateSubcontractingOrderDataVo updateSubcontractingOrderDataVo = new UpdateSubcontractingOrderDataVo();
            updateSubcontractingOrderDataVo.setOutWeight(wmsStockInfo.getWsiNetWeight());
            updateSubcontractingOrderDataVo.setMaterialCode(pickingOutsource.getMaterialCode());
            updateSubcontractingOrderDataVo.setSubcontractingOrderNumber(pickingOutsource.getConnectionId());
            boolean b = orderFeignService.updateSubcontractingOrderDataDelete(updateSubcontractingOrderDataVo);
            if (!b) {
                throw new GlobalException("委外订单服务调用失败");
            }

            //删除品质检验单
            pickingRestDbDto.setMessage("撤销成功");
        }
        pickingRestDbDto.setCode("200");
        return pickingRestDbDto;
    }

    /**
     * 拣货完成
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean finishProduction(Long id) throws Exception {
        //判断当前页面是否有配置送检和交接，如果有则生成品检单

        //获取菜单id
        Long menuId = feignService.getIdByMenuName("委外发货");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = com.alibaba.fastjson2.JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

        //查出生产领料信息单
        PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(id);

        //判断是否有检验
        int docInspectionMark = sysDocument.getDocInspectionMark();
        //如果有检验
        if (docInspectionMark == 1) {

            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource.getMaterialCode()));

            //生成品质检验单
            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
            //添加类别，编码，物料类别
            qualityInspectionDocumentVo.setMaterialCode(pickingOutsource.getMaterialCode());
            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
            qualityInspectionDocumentVo.setAssociatedNo(pickingOutsource.getWodDocNum());
            qualityInspectionDocumentVo.setModeType(2);
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
            //查询当前明细表中的所有物料号码
            List<PickingOutsourceDetail> stockOutInfoDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

            String batchNum = "";

            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                if (j == 0) {
                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                } else {
                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                    }
                }

                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getMaterialNumber());
                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
            }
            qualityInspectionDocumentVo.setBatchNo(batchNum);

            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
            //修改单据状态为待检验
            pickingOutsource.setWodStatus(9);
            return pickingOutsourceMapper.updateById(pickingOutsource) > 0;
        }

        //判断是否有交接
        int docHandoverMark = sysDocument.getDocHandoverMark();
        //有交接
        if (docHandoverMark == 1) {
            //修改单据状态为待交接
            pickingOutsource.setWodStatus(10);
            return pickingOutsourceMapper.updateById(pickingOutsource) > 0;
        }

        //判断是否有超收
        int docHairMark = sysDocument.getDocHairMark();

        //修改单据状态为已完成
        pickingOutsource.setWodStatus(7);

        //删除库存
        List list = new ArrayList<WmsStockInfo>();

        List<PickingOutsourceDetail> pickingOutsourceDetailList3 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

        for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList3) {
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
            list.add(wmsStockInfo);
        }
        wmsStockInfoMapper.deleteBatchIds(list);

        return pickingOutsourceMapper.updateById(pickingOutsource) > 0;

    }

    /**
     * 拣货撤销
     *
     * @param id
     * @return
     */
    @Override
    public boolean repealProduction(Long id) {
        //修改单据状态为待出库
        PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(id);
        pickingOutsource.setWodStatus(5);
        //实际重量，出库重量，出库数量清空
        pickingOutsource.setActualNumber(0.0);
        pickingOutsource.setOutgoingNumber(0);
        pickingOutsource.setOutgoingWeight(0.0);
        //交接数量，交接重量清空
        pickingOutsource.setOverWeight(0.0);
        pickingOutsource.setOverNum(0);
        pickingOutsourceMapper.updateById(pickingOutsource);

        //查询明细
        List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

        //日志表集合
        List<OutboundLog> outboundLogList = new ArrayList<>();

        //遍历
        for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
            //将仓库中的物料全修改为在库
            //修改仓库状态为在库
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
            wmsStockInfo.setWsiMaterialStatus(2);
            wmsStockInfoMapper.updateById(wmsStockInfo);

            OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, wmsStockInfo.getWsiMaterialNumber()));
            outboundLogList.add(outboundLog);
        }
        //删除日志表中的数据
        outboundLogService.removeBatchByIds(outboundLogList);

        //删除品质检验单
        qualityFeginService.removeDoc(pickingOutsource.getWodDocNum());
        //删除所有明细
        int i = pickingOutsourceDetailMapper.delete(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

        UpdateSubcontractingOrderDataVo updateSubcontractingOrderDataVo = new UpdateSubcontractingOrderDataVo();
        updateSubcontractingOrderDataVo.setOutWeight(pickingOutsource.getActualNumber());
        updateSubcontractingOrderDataVo.setMaterialCode(pickingOutsource.getMaterialCode());
        updateSubcontractingOrderDataVo.setSubcontractingOrderNumber(pickingOutsource.getConnectionId());
        boolean b = orderFeignService.updateSubcontractingOrderDataDelete(updateSubcontractingOrderDataVo);
        if (!b) {
            throw new GlobalException("委外订单服务调用失败");
        }

        return i > 0;
    }

    /**
     * 交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestHandoverDto overProduction(PickingRestDbVo pickingRestDbVo) {
        //获取步骤
        int step = pickingRestDbVo.getExecutionOrder();
        //获取输入值
        String inputValue = pickingRestDbVo.getInputValue();
        //返回值
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();
        //获取菜单id
        Long menuId = feignService.getIdByMenuName("委外发货");
        //交接方式
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //拿到交接方式
        int jjType = sysDocument.getDocHandoverMethod();

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        if (step == 1) {


            //校验员工编号
            AjaxResult byUserName = remoteUserService.getByUserName(pickingRestDbVo.getInputValue());
            SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

            if (userInfo.getUserName() == null) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                return pickingRestHandoverDto;
            }

            //返回交接人
            pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
            pickingRestHandoverDto.setDocHandoverMethod(jjType);


            if (jjType == 1) {
                pickingRestHandoverDto.setMessage("请输入物料条码");
            } else if (jjType == 2) {
                pickingRestHandoverDto.setMessage("请输入批次号");
            } else if (jjType == 3) {
                PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());

                pickingRestDbVo.setInputValue(pickingOutsource.getWodDocNum());

                //查询物料单位
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource.getMaterialCode()));

                //判断是否存在明细表中
                List<PickingOutsourceDetail> pickingOutsourceDetailList1 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingRestDbVo.getInputValue()).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
                if (pickingOutsourceDetailList1 == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //查询当前单据号在明细中是否存在，且状态为待交接
                List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingRestDbVo.getInputValue()).eq(PickingOutsourceDetail::getStatus, 2).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
                if (pickingOutsourceDetailList.size() == 0) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败,请核实后再录入");
                    return pickingRestHandoverDto;
                } else {
                    //查出当前为待交接状态的单据明细,算出总净重和总数量
                    Double sumPiHao = pickingOutsourceDetailMapper.getDoc(pickingRestDbVo.getInputValue());
                    //总数量
                    long sumNum = pickingOutsourceDetailList.size();

                    //出库重量
                    Double allotAmount = pickingOutsource.getOutgoingWeight();

                    //返回计划/实际
                    Double overWeight = pickingOutsource.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    //(实际交接)
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(sumPiHao));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    pickingOutsource.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitMap.get(publicGoods.getMaterialUnit()));


                    //保存交接数量，交接重量
                    Integer overNum = pickingOutsource.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    int jjSum = (int) sumNum;
                    pickingOutsource.setOverNum(overNum + jjSum);

                    //取出关节人
                    String closeUser = pickingOutsource.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = SecurityUtils.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        pickingOutsource.setCloseMan(name);
                    }

                    if (jj == 1) {
                        if (closeUser == null || "".equals(closeUser)) {
                            pickingOutsource.setCloseMan(name);
                        } else {
                            pickingOutsource.setCloseMan("," + name);
                        }
                    }
                    pickingOutsource.setCloseTime(new Date());


                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(pickingOutsource.getOutgoingNumber() + "/" + pickingOutsource.getOverNum());

                    for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
                        //修改物料状态明细为已出库
                        pickingOutsourceDetail.setStatus("3");
                        pickingOutsourceDetailMapper.updateById(pickingOutsourceDetail);
                    }


                    //判断是否所有物料没有待交接的状态
                    List<PickingOutsourceDetail> pickingOutsourceDetailList2 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getStatus, 2).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                    if (pickingOutsourceDetailList2.size() == 0) {
                        //修改单据状态为已完成
                        pickingOutsource.setWodStatus(7);
                        //删除库存
                        List list = new ArrayList<WmsStockInfo>();

                        List<PickingOutsourceDetail> pickingOutsourceDetailList3 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                        for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList3) {
                            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
                            list.add(wmsStockInfo);
                        }
                        wmsStockInfoMapper.deleteBatchIds(list);

                    }
                    boolean b = updateById(pickingOutsource);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("单据号:" + pickingRestDbVo.getInputValue() + ",总净重" + sumPiHao + "数量:" + sumNum + ",交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                }
            }
            pickingRestHandoverDto.setResultCode("200");
            return pickingRestHandoverDto;

        } else if (step == 2) {
            //如果是单个物料交接
            if (jjType == 1) {
                //查询当前的出库单信息
                PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());

                //查询物料单位
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource.getMaterialCode()));


                //查询出库明细
                PickingOutsourceDetail pickingOutsourceDetail = pickingOutsourceDetailMapper.selectOne(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getMaterialNumber, inputValue).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
                if (pickingOutsourceDetail == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //判断当前物料是否属于待交接
                if (!"2".equals(pickingOutsourceDetail.getStatus())) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("不可重复交接");
                    return pickingRestHandoverDto;
                } else {
                    //出库重量
                    Double allotAmount = pickingOutsource.getOutgoingWeight();

                    Double overWeight = pickingOutsource.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }

                    //(实际交接)
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(pickingOutsourceDetail.getTheWeight()));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    pickingOutsource.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitMap.get(publicGoods.getMaterialUnit()));

                    Integer overNum = pickingOutsource.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    //保存交接数量，交接重量
                    pickingOutsource.setOverNum(overNum + 1);

                    //取出关节人
                    String closeUser = pickingOutsource.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = SecurityUtils.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        pickingOutsource.setCloseMan(name);
                    }


                    if (jj == 1) {
                        pickingOutsource.setCloseMan("," + name);
                    }
                    pickingOutsource.setCloseTime(new Date());

                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(pickingOutsource.getOutgoingNumber() + "/" + pickingOutsource.getOverNum());

                    //修改物料状态明细为已出库
                    pickingOutsourceDetail.setStatus("3");
                    pickingOutsourceDetailMapper.updateById(pickingOutsourceDetail);


                    //判断是否所有物料没有待交接的状态
                    List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getStatus, 2).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
                    if (pickingOutsourceDetailList.size() == 0) {
                        //修改单据状态为已完成
                        pickingOutsource.setWodStatus(7);

                    }
                    //删除库存
                    wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
                    boolean b = updateById(pickingOutsource);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }
                    //消息提示
                    pickingRestHandoverDto.setMessage("物料号码:" + pickingRestDbVo.getInputValue() + ",净重" + pickingOutsourceDetail.getTheWeight() + "数量:1,交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                }
            } else if (jjType == 2) {
                PickingOutsource pickingOutsource = pickingOutsourceMapper.selectById(pickingRestDbVo.getId());

                //查询物料单位
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingOutsource.getMaterialCode()));

                //判断是否存在明细表中
                List<PickingOutsourceDetail> pickingOutsourceDetailList1 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getBatchNumber, pickingRestDbVo.getInputValue()).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
                if (pickingOutsourceDetailList1 == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //查询当前批号在明细中是否存在，且状态为待交接
                List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getBatchNumber, pickingRestDbVo.getInputValue()).eq(PickingOutsourceDetail::getStatus, 2).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));
                if (pickingOutsourceDetailList.size() == 0) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("不可重复交接");
                    return pickingRestHandoverDto;
                } else {
                    //查出当前为待交接状态的批次，算出总净重和总数量
                    Double sumPiHao = pickingOutsourceDetailMapper.getPiHao(pickingRestDbVo.getInputValue());
                    //总数量
                    long sumNum = pickingOutsourceDetailList.size();

                    //出库重量
                    Double allotAmount = pickingOutsource.getOutgoingWeight();

                    //返回计划/实际
                    Double overWeight = pickingOutsource.getOverWeight();
                    //(实际交接)
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(sumPiHao));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    pickingOutsource.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitMap.get(publicGoods.getMaterialUnit()));


                    //保存交接数量，交接重量
                    Integer overNum = pickingOutsource.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    int jjSum = (int) sumNum;
                    pickingOutsource.setOverNum(overNum + jjSum);

                    //取出关节人
                    String closeUser = pickingOutsource.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = SecurityUtils.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        pickingOutsource.setCloseMan(name);
                    }

                    if (jj == 1) {
                        if (closeUser == null || "".equals(closeUser)) {
                            pickingOutsource.setCloseMan(name);
                        } else {
                            pickingOutsource.setCloseMan("," + name);
                        }
                    }
                    pickingOutsource.setCloseTime(new Date());

                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(pickingOutsource.getOutgoingNumber() + "/" + pickingOutsource.getOverNum());

                    for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
                        //修改物料状态明细为已出库
                        pickingOutsourceDetail.setStatus("3");

                    }
                    pickingOutsourceDetailService.updateBatchById(pickingOutsourceDetailList);

                    //判断是否所有物料没有待交接的状态
                    List<PickingOutsourceDetail> pickingOutsourceDetailList2 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getStatus, 2).eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                    if (pickingOutsourceDetailList2.size() == 0) {
                        //修改单据状态为已完成
                        pickingOutsource.setWodStatus(7);
                        //删除库存
                        List list = new ArrayList<WmsStockInfo>();

                        List<PickingOutsourceDetail> pickingOutsourceDetailList3 = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                        for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList3) {
                            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
                            list.add(wmsStockInfo);
                        }
                        wmsStockInfoMapper.deleteBatchIds(list);
                    }
                    boolean b = updateById(pickingOutsource);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + ",总净重" + sumPiHao + "数量:" + sumNum + ",交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                }

            } else if (jjType == 3) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("请勿重复交接");

            }
        }
        pickingRestHandoverDto.setResultCode("200");
        return pickingRestHandoverDto;
    }

    /**
     * 审核单据
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickOutSourceReview(OrderReviewVo orderReviewVo) {

        PickingOutsource pickingOutsource = getById(orderReviewVo.getId());
        if (pickingOutsource.getWodStatus() == 2 || pickingOutsource.getWodStatus() == 3) {
            String perms = "warehouse:outbound:subcontract:examine";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = pickingOutsource.getWodDocNum();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 9, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    pickingOutsource.setWodStatus(5);
                    if (pickingOutsource.getReviewBy() == null) {
                        pickingOutsource.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingOutsource.setReviewBy(pickingOutsource.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingOutsource.setReviewTime(new Date());

                    feignService.updateStatus(3, pickingOutsource.getWodDocNum(), "委外发货");

                    return updateById(pickingOutsource);
                } else if (data == 2) {
                    pickingOutsource.setWodStatus(3);
                    if (pickingOutsource.getReviewBy() == null) {
                        pickingOutsource.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingOutsource.setReviewBy(pickingOutsource.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingOutsource.setReviewTime(new Date());
                    return updateById(pickingOutsource);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    pickingOutsource.setWodStatus(4);
                    if (pickingOutsource.getReviewBy() == null) {
                        pickingOutsource.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingOutsource.setReviewBy(pickingOutsource.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingOutsource.setReviewTime(new Date());

                    SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
                    sysWorkbenchAuditAgentVo.setDocConfig("warehouse:outbound:subcontract:examine");
                    sysWorkbenchAuditAgentVo.setReceiptName("委外发货");
                    sysWorkbenchAuditAgentVo.setReceiptNumber(pickingOutsource.getWodDocNum());//

                    sysWorkbenchAuditAgentVo.setPassFlag("1");
                    sysWorkbenchAuditAgentVo.setCreateName(pickingOutsource.getCreateUser());
                    sysWorkbenchAuditAgentVo.setStatus(2);//待处理
                    sysWorkbenchAuditAgentVo.setReceiptContent("有单据未通过,请及时查看");

                    feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                    return updateById(pickingOutsource);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }
    }

    /**
     * 修改仓库状态Feign
     *
     * @param updateDocVo
     * @return
     */
    @Override
    public boolean outSourceUpdateStatus(UpdateDocVo updateDocVo) {
        //获取菜单id
        Long menuId = feignService.getIdByMenuName("委外发货");
        //交接方式
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);


        //判断是否有交接
        int docHandoverMark = sysDocument.getDocHandoverMark();
        //如果有交接，修改单据状态和物料明细状态为代交接
        if (docHandoverMark == 1) {
            PickingOutsource pickingOutsource = pickingOutsourceMapper.selectOne(new QueryWrapper<PickingOutsource>().lambda().eq(PickingOutsource::getWodDocNum, updateDocVo.getDocNum()));
            pickingOutsource.setWodStatus(10);//待交接
            updateById(pickingOutsource);
            List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, updateDocVo.getDocNum()));
            for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
                pickingOutsourceDetail.setStatus("2");
            }
            return pickingOutsourceDetailService.updateBatchById(pickingOutsourceDetailList);

        } else {
            PickingOutsource pickingOutsource = pickingOutsourceMapper.selectOne(new QueryWrapper<PickingOutsource>().lambda().eq(PickingOutsource::getWodDocNum, updateDocVo.getDocNum()));
            pickingOutsource.setWodStatus(7);//已完成
            updateById(pickingOutsource);
            List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, updateDocVo.getDocNum()));

            List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();

            for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
                pickingOutsourceDetail.setStatus("3");

                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
                wmsStockInfoList.add(wmsStockInfo);

            }
            wmsStockInfoService.removeBatchByIds(wmsStockInfoList);
            return pickingOutsourceDetailService.updateBatchById(pickingOutsourceDetailList);
        }

    }

    @Override
    public SchemeDto point(Long id) {
        PickingOutsource byId = getById(id);
        SchemeVo schemeVo = new SchemeVo();
        schemeVo.setMaterialCode(byId.getMaterialCode());
        schemeVo.setAssociatedDetails("2");
        return pickingSchemeService.getSchemeData(schemeVo);
    }

    /**
     * 新增（委外订单fegin调用）
     *
     * @param subcontractReceiptOtherVo
     * @return
     */
    @Override
    public boolean addPickingOutsource(SubcontractReceiptOtherVo subcontractReceiptOtherVo) {

        List<SubcontractingOrderMaterialDetailVo> materialDetailList = subcontractReceiptOtherVo.getMaterialDetailList();
        List<PickingOutsource> pickingOutsourceList = new ArrayList<>();
        for (SubcontractingOrderMaterialDetailVo entity : materialDetailList) {
            PickingOutsource pickingOutsource = new PickingOutsource();
            String sn = feignService.getAuthorityCoding("warehouse:outbound:subcontract:list");
            if (sn == null) {
                throw new GlobalException("该单据未进行配置,无法生成单据编码");
            }
            pickingOutsource.setWodDocNum(sn)
                    .setWodStatus(1)
                    .setCreateUser(SecurityUtils.getUsername())
                    .setCreateTime(new Date())
                    .setDocumentType(DocumentTypeEnum.PICKING_OUTSOURCE.getCode())
                    .setPlannedWeight(Double.parseDouble(entity.getWarehouseWeight()))
                    .setMaterialCode(entity.getMaterialCode())
                    .setTransceiverType(1)
                    .setCategory(String.valueOf(entity.getBomDetailType()))
                    .setDeptId(SecurityUtils.getDeptId())
                    .setGenerationMode(GenerationMethodEnum.AUTO_GENERATE.getCode())
                    .setConnectionId(entity.getSubcontractingOrderNum())
                    .setFabricatorsId(entity.getConverterId());
            pickingOutsourceList.add(pickingOutsource);
        }
        return saveBatch(pickingOutsourceList);
    }

    /**
     * 关结委外发货
     *
     * @param pickingOutsourceVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean closeOutsourceFeign(PickingOutsourceFeignVo pickingOutsourceVo) {


        //已完成已关结单据不可重复关结
        List<PickingOutsource> pickingOutsourceList = pickingOutsourceMapper.selectList(new QueryWrapper<PickingOutsource>().lambda().eq(PickingOutsource::getConnectionId, pickingOutsourceVo.getConnectionId()));
        for (PickingOutsource pickingOutsource : pickingOutsourceList) {
            Integer wodStatus = pickingOutsource.getWodStatus();

            if (wodStatus == 8 || wodStatus == 7) {
                throw new GlobalException("不可对已关结和已完成状态的单据进行重复关结");
            }


            try {
                //如果单据状态是待检验，入库的物料显示在库，关联品质检验单状态更新为撤销
                if (wodStatus == 9 || wodStatus == 10 || wodStatus == 6) {
                    //根据单号获取生产领料单明细
                    List<PickingOutsourceDetail> pickingOutsourceDetailList = pickingOutsourceDetailMapper.selectList(new QueryWrapper<PickingOutsourceDetail>().lambda().eq(PickingOutsourceDetail::getWodDocNum, pickingOutsource.getWodDocNum()));

                    ArrayList<WmsStockInfo> wmsStockInfos = new ArrayList<>();

                    for (PickingOutsourceDetail pickingOutsourceDetail : pickingOutsourceDetailList) {
                        WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingOutsourceDetail.getMaterialNumber()));
                        wmsStockInfos.add(wmsStockInfo);
                    }

                    if (wmsStockInfos.size() != 0) {
                        boolean b = wmsStockInfoService.removeBatchByIds(wmsStockInfos);
                    }


                    if (wodStatus == 9) {
                        //如果是待检验删除品质检验单
                        UpdateQualityStatusVo updateQualityStatusVo = new UpdateQualityStatusVo();
                        updateQualityStatusVo.setStatus(8);
                        updateQualityStatusVo.setAssociatedNo(pickingOutsource.getWodDocNum());
                        AjaxResult ajaxResult = qualityFeginService.updateQualityInspectionDocument(updateQualityStatusVo);


                        if (!"200".equals(ajaxResult.get("code").toString())) {
                            throw new GlobalException("服务调用失败");
                        }

                    }
                }
            } catch (Exception e) {
                throw new GlobalException("关结失败");
            }


            //取出关结人
            String closeMan = pickingOutsource.getCloseMan();
            if (closeMan != null) {
                closeMan = closeMan + "," + SecurityUtils.getUsername();
            } else {
                closeMan = SecurityUtils.getUsername();
            }

            //修改单据状态未关结，修改关结原因，修改关结人，修改关结时间
            pickingOutsource
                    .setWodStatus(8).setCloseTime(new Date())
                    .setCloseMan(closeMan)
                    .setCloseCause(pickingOutsourceVo.getCloseCause());
            updateById(pickingOutsource);
        }
       return pickingOutsourceList.size() > 0;
    }

}
